//
//  MusicCollectionViewCell.m
//  CapriceMusic
//
//  Created by 蒋恩浩 on 16/1/18.
//  Copyright © 2016年 MYX. All rights reserved.
//

#import "MusicCollectionViewCell.h"

#define addSeconds 0

@interface MusicCollectionViewCell ()<UITableViewDataSource, UITableViewDelegate>

// 当前行
@property (nonatomic, assign) NSInteger currentRow;
// 歌词
@property (nonatomic, strong) NSMutableArray *lrcDataSource;
// 时间
@property (nonatomic, strong) NSMutableArray *timeDataSource;

@end

@implementation MusicCollectionViewCell

- (instancetype)initWithFrame:(CGRect)frame {
    
    self = [super initWithFrame:frame];
    if (self) {

        [self createView];
    }
    return self;
}

// 歌词id
- (void)setContentId:(NSString *)contentId {
    
    if (_contentId != contentId) {

        _contentId = contentId;
        [self getLrcData];
    }
}

// 时间
- (void)setCurrentPlayerTime:(CGFloat)currentPlayerTime {
    
    if (_currentPlayerTime != currentPlayerTime) {
        
        _currentPlayerTime = currentPlayerTime;
    }
}

#pragma mark - 网络请求获取歌词
- (void)getLrcData {

    [JEHNetWorkTool getWithUrl:kLrcGETTURL parameter:@{@"contentid": self.contentId, @"ua": @"Iphone_Sst", @"version":@"4.243"} httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
        
        if (result) {

            [self parseLrcToolWithLrcString:result[@"lrc"]];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.tableView reloadData];
        });
    } fail:^(NSError *error) {
        
        NSLog(@"%@", error);
    }];
}

- (void)parseLrcToolWithLrcString:(NSString *)lrcString {
    
    self.lrcDataSource = [NSMutableArray arrayWithCapacity:0];
    self.timeDataSource = [NSMutableArray arrayWithCapacity:0];
    // 获取歌词数组(分离器方法)
    NSArray *lrcArray = [lrcString componentsSeparatedByString:@"\n"];
    for (NSString *string in lrcArray) {
        
        // 过滤掉不需要的行
        if ([string hasPrefix:@"[ti:"] || [string hasPrefix:@"[ar:"] || [string hasPrefix:@"[al:"] || ![string hasPrefix:@"["] || [string hasPrefix:@"[high:"] || [string hasPrefix:@"[by:"]) continue;
        // 时间和歌词分开([00:00.00 和 夜空中最闪亮的)
        NSArray *array = [string componentsSeparatedByString:@"]"];
        NSString *time = array[0];
        // 去掉@"["
        time = [time substringFromIndex:1];
        // 时间去掉@":"
        NSArray *timeArray = [time componentsSeparatedByString:@":"];
        // 分
        NSInteger minutes = [timeArray[0] integerValue];
        // 秒
        NSInteger seconds = [[timeArray[1] componentsSeparatedByString:@"."][0] integerValue];
        // 毫秒
        NSInteger millisecond = [[timeArray[1] componentsSeparatedByString:@"."][1] integerValue];
        // 总时间 s
        CGFloat times = minutes * 60 + seconds + millisecond * 0.01;
        NSNumber *number = [NSNumber numberWithFloat:times];
        [self.timeDataSource addObject:number];
        // 歌词
        NSString *lrc = array[1];
        [self.lrcDataSource addObject:lrc];
    }
}

#pragma mark - 创建视图
- (void)createView {
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLineEtched;
    [self.tableView registerClass:[LrcTableViewCell class] forCellReuseIdentifier:@"LrcTableViewCell"];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
    self.tableView.backgroundColor = [UIColor clearColor];
    [self addSubview:self.tableView];
    // 歌词timer
    self.lrcTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(lrcTimerAction) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.lrcTimer forMode:NSRunLoopCommonModes];
}

#pragma mark - 歌词timer
- (void)lrcTimerAction {
    
    self.currentPlayerTime++;
    [self.tableView reloadData];
}

#pragma mark - 重载布局
- (void)applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes {
    [super applyLayoutAttributes:layoutAttributes];
    
    self.tableView.frame = self.bounds;
}

#pragma mark - tableView代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (self.lrcDataSource.count > 0 && self.timeDataSource.count > 0) {
        
        return self.lrcDataSource.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    LrcTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LrcTableViewCell"];
    if (self.lrcDataSource.count > 0 && self.timeDataSource.count > 0) {
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.lrcText = self.lrcDataSource[indexPath.row];
        NSNumber *number1 = self.timeDataSource[indexPath.row];
        NSNumber *number2 = nil;
        if (indexPath.row + 1 < self.timeDataSource.count) {
            
            number2 = self.timeDataSource[indexPath.row + 1];
        }
        if (self.currentPlayerTime + addSeconds >= number1.floatValue && self.currentPlayerTime + addSeconds < number2.floatValue) {
            
            cell.color = [UIColor greenColor];
            [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
        } else {
            cell.color = [UIColor grayColor];
        }
    }
    return cell;
}

#pragma mark - tableView点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    NSNumber *number = self.timeDataSource[indexPath.row];
    self.currentPlayerTime = number.floatValue;
    [self.tableView reloadData];
    [self.delegate progressBarSyncToLrcWithCurrentPlayerTime:self.currentPlayerTime];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return self.height / 2 - 25;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return self.height / 2 - 25;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 50;
}

#pragma mark - 拖动进度条歌词跟着动
- (void)lrcSyncToProgressBar {
    
    for (NSInteger i = 0; i < self.timeDataSource.count; i++) {
        
        if (i + 1 < self.timeDataSource.count) {
            
            NSNumber *number1 = self.timeDataSource[i];
            NSNumber *number2 = self.timeDataSource[i + 1];
            if (self.currentPlayerTime + addSeconds >= number1.floatValue && self.currentPlayerTime + addSeconds < number2.floatValue) {
                
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
            }
        }
    }
}


@end





















